"use client";

import React, { useState, useRef, useEffect } from "react";
import dynamic from "next/dynamic";
import { format } from "sql-formatter";
import "bootstrap/dist/css/bootstrap.min.css";

// 动态导入Monaco编辑器以避免SSR问题
const MonacoEditor = dynamic(() => import("@monaco-editor/react"), {
  ssr: false,
  loading: () => (
    <div className="editor-loading">
      <div className="loading-spinner"></div>
      <div>加载编辑器中...</div>
    </div>
  ),
});

export default function SqlContent({
  isDarkMode,
  sqlCode: externalSqlCode,
  setSqlCode: setExternalSqlCode,
}) {
  const [sqlCode, setSqlCode] = useState(
    "SELECT * FROM t_sys_account WHERE id > 1;"
  );
  const [queryResults, setQueryResults] = useState([]);
  const [isExecuting, setIsExecuting] = useState(false);
  const [executionTime, setExecutionTime] = useState(null);
  const [errorMessage, setErrorMessage] = useState("");
  const [validationErrors, setValidationErrors] = useState([]);
  const [editorMounted, setEditorMounted] = useState(false);

  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalRecords, setTotalRecords] = useState(0);

  // 监听外部SQL代码变化
  useEffect(() => {
    if (externalSqlCode && externalSqlCode !== sqlCode) {
      setSqlCode(externalSqlCode);
      // 如果编辑器已挂载，更新编辑器内容
      if (editorRef.current) {
        editorRef.current.setValue(externalSqlCode);
      }
    }
  }, [externalSqlCode, sqlCode]);

  // 当内部SQL代码变化时，同步到外部
  const handleSqlCodeChange = (value) => {
    setSqlCode(value);
    if (setExternalSqlCode) {
      setExternalSqlCode(value);
    }
  };

  const editorRef = useRef(null);

  // Monaco编辑器配置
  const editorOptions = {
    selectOnLineNumbers: true,
    roundedSelection: false,
    readOnly: false,
    cursorStyle: "line",
    automaticLayout: true,
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    fontSize: 14,
    lineHeight: 20,
    fontFamily: "Consolas, Monaco, monospace",
    wordWrap: "on",
    theme: isDarkMode ? "vs-dark" : "vs",
    language: "mysql",
    // 优化自动完成配置
    suggest: {
      showKeywords: true,
      showSnippets: true,
      showFunctions: true,
      showVariables: true,
      showClasses: true,
      showStructs: true,
      showInterfaces: true,
      showModules: true,
      showProperties: true,
      showEvents: true,
      showOperators: true,
      showUnits: true,
      showValues: true,
      showConstants: true,
      showEnums: true,
      showEnumMembers: true,
      showColors: true,
      showFiles: true,
      showReferences: true,
      showFolders: true,
      showTypeParameters: true,
      showIssues: true,
      showUsers: true,
      insertMode: "replace", // 替换模式，更好的用户体验
      filterGraceful: true, // 优雅的过滤
      snippetsPreventQuickSuggestions: false, // 允许在代码片段中显示建议
      localityBonus: true, // 本地性加成
      shareSuggestSelections: false, // 不共享建议选择
      selectionHighlight: true, // 高亮选择
      wordBasedSuggestions: true, // 基于单词的建议
    },
    quickSuggestions: {
      other: true,
      comments: false,
      strings: false,
    },
    // 增强的自动完成触发
    quickSuggestionsDelay: 100, // 快速建议延迟（毫秒）
    suggestOnTriggerCharacters: true, // 在触发字符上显示建议
    acceptSuggestionOnCommitCharacter: true, // 在提交字符上接受建议
    acceptSuggestionOnEnter: "on", // 在回车时接受建议
    tabCompletion: "on", // Tab键完成
    wordBasedSuggestions: true, // 基于单词的建议
    // 参数提示
    parameterHints: {
      enabled: true,
      cycle: true,
    },
    // 悬停提示
    hover: {
      enabled: true,
      delay: 300,
      sticky: true,
    },
  };

  // 处理编辑器挂载
  const handleEditorDidMount = (editor, monaco) => {
    editorRef.current = editor;
    setEditorMounted(true);

    // 注册MySQL语言支持
    monaco.languages.register({ id: "mysql" });

    // 设置MySQL语法高亮
    monaco.languages.setMonarchTokensProvider("mysql", {
      tokenizer: {
        root: [
          // SQL关键字
          [
            /\b(SELECT|FROM|WHERE|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|TABLE|INDEX|DATABASE|SCHEMA|VIEW|PROCEDURE|FUNCTION|TRIGGER|IF|ELSE|ELSEIF|WHILE|FOR|LOOP|REPEAT|UNTIL|CASE|WHEN|THEN|END|BEGIN|DECLARE|SET|CALL|RETURN|LEAVE|ITERATE|HANDLER|CONDITION|CURSOR|OPEN|CLOSE|FETCH|PREPARE|EXECUTE|DEALLOCATE|START|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|LOCK|UNLOCK|GRANT|REVOKE|FLUSH|RESET|KILL|SHOW|DESCRIBE|EXPLAIN|ANALYZE|OPTIMIZE|REPAIR|CHECK|CHECKSUM|BACKUP|RESTORE|LOAD|UNLOAD|IMPORT|EXPORT|TRUNCATE|RENAME|COPY|MOVE)\b/i,
            "keyword",
          ],

          // 数据类型
          [
            /\b(INT|INTEGER|BIGINT|SMALLINT|TINYINT|DECIMAL|NUMERIC|FLOAT|DOUBLE|REAL|BIT|BOOLEAN|SERIAL|CHAR|VARCHAR|TEXT|TINYTEXT|MEDIUMTEXT|LONGTEXT|BINARY|VARBINARY|BLOB|TINYBLOB|MEDIUMBLOB|LONGBLOB|DATE|TIME|DATETIME|TIMESTAMP|YEAR|ENUM|SET|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)\b/i,
            "type",
          ],

          // 函数
          [
            /\b(COUNT|SUM|AVG|MIN|MAX|GROUP_CONCAT|CONCAT|SUBSTRING|LENGTH|UPPER|LOWER|TRIM|LTRIM|RTRIM|REPLACE|REGEXP|LIKE|RLIKE|MATCH|AGAINST|NOW|CURDATE|CURTIME|DATE_FORMAT|DATE_ADD|DATE_SUB|DATEDIFF|TIMESTAMPDIFF|YEAR|MONTH|DAY|HOUR|MINUTE|SECOND|WEEKDAY|DAYOFWEEK|DAYOFYEAR|WEEK|QUARTER|LAST_INSERT_ID|ROW_COUNT|FOUND_ROWS|CONNECTION_ID|DATABASE|USER|VERSION|CHARSET|COLLATION|IF|IFNULL|NULLIF|COALESCE|GREATEST|LEAST|ABS|CEIL|CEILING|FLOOR|ROUND|TRUNCATE|SIGN|SQRT|POWER|EXP|LOG|LOG10|SIN|COS|TAN|ASIN|ACOS|ATAN|ATAN2|DEGREES|RADIANS|PI|RAND|MD5|SHA1|SHA2|PASSWORD|ENCRYPT|DECODE|ENCODE|COMPRESS|UNCOMPRESS|INET_ATON|INET_NTOA)\b/i,
            "predefined",
          ],

          // 操作符
          [
            /\b(AND|OR|NOT|IN|EXISTS|BETWEEN|IS|NULL|TRUE|FALSE|UNKNOWN|ALL|ANY|SOME|UNION|INTERSECT|EXCEPT|DISTINCT|ORDER|BY|GROUP|HAVING|LIMIT|OFFSET|ASC|DESC|INNER|LEFT|RIGHT|FULL|OUTER|JOIN|ON|USING|CROSS|NATURAL|AS|ALIAS)\b/i,
            "operator.word",
          ],

          // 字符串
          [/'([^'\\]|\\.)*'/, "string"],
          [/"([^"\\]|\\.)*"/, "string"],
          [/`([^`\\]|\\.)*`/, "identifier"],

          // 数字
          [/\d*\.\d+([eE][\-+]?\d+)?/, "number.float"],
          [/\d+/, "number"],

          // 注释
          [/--.*$/, "comment"],
          [/#.*$/, "comment"],
          [/\/\*/, "comment", "@comment"],

          // 操作符
          [/[=<>!]+/, "operator"],
          [/[+\-*\/%]/, "operator"],

          // 分隔符
          [/[;,.]/, "delimiter"],
          [/[()[\]{}]/, "bracket"],
        ],

        comment: [
          [/[^\/*]+/, "comment"],
          [/\*\//, "comment", "@pop"],
          [/[\/*]/, "comment"],
        ],
      },
    });

    // 设置自动完成
    monaco.languages.registerCompletionItemProvider("mysql", {
      provideCompletionItems: (model, position) => {
        const word = model.getWordUntilPosition(position);
        const range = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: word.startColumn,
          endColumn: word.endColumn,
        };

        const suggestions = [
          // 基本SQL语句模板
          {
            label: "SELECT",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "SELECT ${1:columns} FROM ${2:table}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "SELECT statement - 查询数据",
            range: range,
          },
          {
            label: "INSERT",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText:
              "INSERT INTO ${1:table} (${2:columns}) VALUES (${3:values})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "INSERT statement - 插入数据",
            range: range,
          },
          {
            label: "UPDATE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText:
              "UPDATE ${1:table} SET ${2:column} = ${3:value} WHERE ${4:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "UPDATE statement - 更新数据",
            range: range,
          },
          {
            label: "DELETE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "DELETE FROM ${1:table} WHERE ${2:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "DELETE statement - 删除数据",
            range: range,
          },
          {
            label: "CREATE TABLE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText:
              "CREATE TABLE ${1:table_name} (\n  ${2:column_name} ${3:data_type},\n  ${4:column_name2} ${5:data_type2}\n)",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "CREATE TABLE statement - 创建表",
            range: range,
          },
          {
            label: "ALTER TABLE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText:
              "ALTER TABLE ${1:table_name} ${2:ADD|DROP|MODIFY} ${3:column_definition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "ALTER TABLE statement - 修改表结构",
            range: range,
          },
          {
            label: "DROP TABLE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "DROP TABLE ${1:table_name}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "DROP TABLE statement - 删除表",
            range: range,
          },

          // SQL关键字
          {
            label: "FROM",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "FROM ${1:table}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "FROM clause - 指定数据源表",
            range: range,
          },
          {
            label: "WHERE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "WHERE ${1:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "WHERE clause - 过滤条件",
            range: range,
          },
          {
            label: "ORDER BY",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "ORDER BY ${1:column} ${2:ASC|DESC}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "ORDER BY clause - 排序",
            range: range,
          },
          {
            label: "GROUP BY",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "GROUP BY ${1:column}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "GROUP BY clause - 分组",
            range: range,
          },
          {
            label: "HAVING",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "HAVING ${1:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "HAVING clause - 分组后过滤",
            range: range,
          },
          {
            label: "LIMIT",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "LIMIT ${1:count}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "LIMIT clause - 限制结果数量",
            range: range,
          },
          {
            label: "OFFSET",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "OFFSET ${1:count}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "OFFSET clause - 跳过指定数量的记录",
            range: range,
          },

          // JOIN相关
          {
            label: "INNER JOIN",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "INNER JOIN ${1:table} ON ${2:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "INNER JOIN - 内连接",
            range: range,
          },
          {
            label: "LEFT JOIN",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "LEFT JOIN ${1:table} ON ${2:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "LEFT JOIN - 左连接",
            range: range,
          },
          {
            label: "RIGHT JOIN",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "RIGHT JOIN ${1:table} ON ${2:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "RIGHT JOIN - 右连接",
            range: range,
          },
          {
            label: "FULL OUTER JOIN",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "FULL OUTER JOIN ${1:table} ON ${2:condition}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "FULL OUTER JOIN - 全外连接",
            range: range,
          },

          // 聚合函数
          {
            label: "COUNT",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "COUNT(${1:column|*})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "COUNT() - 计算行数",
            range: range,
          },
          {
            label: "SUM",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "SUM(${1:column})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "SUM() - 求和",
            range: range,
          },
          {
            label: "AVG",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "AVG(${1:column})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "AVG() - 平均值",
            range: range,
          },
          {
            label: "MAX",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "MAX(${1:column})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "MAX() - 最大值",
            range: range,
          },
          {
            label: "MIN",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "MIN(${1:column})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "MIN() - 最小值",
            range: range,
          },

          // 字符串函数
          {
            label: "CONCAT",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "CONCAT(${1:string1}, ${2:string2})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "CONCAT() - 字符串连接",
            range: range,
          },
          {
            label: "SUBSTRING",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "SUBSTRING(${1:string}, ${2:start}, ${3:length})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "SUBSTRING() - 截取子字符串",
            range: range,
          },
          {
            label: "LENGTH",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "LENGTH(${1:string})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "LENGTH() - 字符串长度",
            range: range,
          },
          {
            label: "UPPER",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "UPPER(${1:string})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "UPPER() - 转换为大写",
            range: range,
          },
          {
            label: "LOWER",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "LOWER(${1:string})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "LOWER() - 转换为小写",
            range: range,
          },
          {
            label: "TRIM",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "TRIM(${1:string})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "TRIM() - 去除首尾空格",
            range: range,
          },

          // 日期时间函数
          {
            label: "NOW",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "NOW()",
            documentation: "NOW() - 当前日期时间",
            range: range,
          },
          {
            label: "CURDATE",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "CURDATE()",
            documentation: "CURDATE() - 当前日期",
            range: range,
          },
          {
            label: "CURTIME",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "CURTIME()",
            documentation: "CURTIME() - 当前时间",
            range: range,
          },
          {
            label: "DATE_FORMAT",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "DATE_FORMAT(${1:date}, '${2:%Y-%m-%d}')",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "DATE_FORMAT() - 格式化日期",
            range: range,
          },
          {
            label: "DATEDIFF",
            kind: monaco.languages.CompletionItemKind.Function,
            insertText: "DATEDIFF(${1:date1}, ${2:date2})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "DATEDIFF() - 计算日期差",
            range: range,
          },

          // 数据类型
          {
            label: "INT",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "INT",
            documentation: "INT - 整数类型",
            range: range,
          },
          {
            label: "VARCHAR",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "VARCHAR(${1:255})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "VARCHAR - 可变长度字符串",
            range: range,
          },
          {
            label: "TEXT",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "TEXT",
            documentation: "TEXT - 长文本类型",
            range: range,
          },
          {
            label: "DATETIME",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "DATETIME",
            documentation: "DATETIME - 日期时间类型",
            range: range,
          },
          {
            label: "DATE",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "DATE",
            documentation: "DATE - 日期类型",
            range: range,
          },
          {
            label: "TIME",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "TIME",
            documentation: "TIME - 时间类型",
            range: range,
          },
          {
            label: "DECIMAL",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "DECIMAL(${1:10}, ${2:2})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "DECIMAL - 精确数值类型",
            range: range,
          },
          {
            label: "FLOAT",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "FLOAT",
            documentation: "FLOAT - 浮点数类型",
            range: range,
          },
          {
            label: "DOUBLE",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "DOUBLE",
            documentation: "DOUBLE - 双精度浮点数",
            range: range,
          },
          {
            label: "BOOLEAN",
            kind: monaco.languages.CompletionItemKind.TypeParameter,
            insertText: "BOOLEAN",
            documentation: "BOOLEAN - 布尔类型",
            range: range,
          },

          // 约束和修饰符
          {
            label: "PRIMARY KEY",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "PRIMARY KEY",
            documentation: "PRIMARY KEY - 主键约束",
            range: range,
          },
          {
            label: "FOREIGN KEY",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText:
              "FOREIGN KEY (${1:column}) REFERENCES ${2:table}(${3:column})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "FOREIGN KEY - 外键约束",
            range: range,
          },
          {
            label: "NOT NULL",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "NOT NULL",
            documentation: "NOT NULL - 非空约束",
            range: range,
          },
          {
            label: "UNIQUE",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "UNIQUE",
            documentation: "UNIQUE - 唯一约束",
            range: range,
          },
          {
            label: "AUTO_INCREMENT",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "AUTO_INCREMENT",
            documentation: "AUTO_INCREMENT - 自动递增",
            range: range,
          },
          {
            label: "DEFAULT",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "DEFAULT ${1:value}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "DEFAULT - 默认值",
            range: range,
          },

          // 逻辑操作符
          {
            label: "AND",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "AND",
            documentation: "AND - 逻辑与",
            range: range,
          },
          {
            label: "OR",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "OR",
            documentation: "OR - 逻辑或",
            range: range,
          },
          {
            label: "NOT",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "NOT",
            documentation: "NOT - 逻辑非",
            range: range,
          },
          {
            label: "IN",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "IN (${1:values})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "IN - 在指定值列表中",
            range: range,
          },
          {
            label: "LIKE",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "LIKE '${1:pattern}'",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "LIKE - 模式匹配",
            range: range,
          },
          {
            label: "BETWEEN",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "BETWEEN ${1:value1} AND ${2:value2}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "BETWEEN - 在指定范围内",
            range: range,
          },
          {
            label: "IS NULL",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "IS NULL",
            documentation: "IS NULL - 为空值",
            range: range,
          },
          {
            label: "IS NOT NULL",
            kind: monaco.languages.CompletionItemKind.Operator,
            insertText: "IS NOT NULL",
            documentation: "IS NOT NULL - 不为空值",
            range: range,
          },

          // 其他常用关键字
          {
            label: "DISTINCT",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "DISTINCT",
            documentation: "DISTINCT - 去重",
            range: range,
          },
          {
            label: "AS",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "AS ${1:alias}",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "AS - 别名",
            range: range,
          },
          {
            label: "UNION",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "UNION",
            documentation: "UNION - 联合查询",
            range: range,
          },
          {
            label: "UNION ALL",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "UNION ALL",
            documentation: "UNION ALL - 联合查询(包含重复)",
            range: range,
          },
          {
            label: "EXISTS",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "EXISTS (${1:subquery})",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "EXISTS - 存在性检查",
            range: range,
          },
          {
            label: "CASE WHEN",
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText:
              "CASE WHEN ${1:condition} THEN ${2:value} ELSE ${3:default_value} END",
            insertTextRules:
              monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            documentation: "CASE WHEN - 条件表达式",
            range: range,
          },
        ];

        return { suggestions };
      },
    });
  };

  // 模拟SQL执行
  const executeSQL = async () => {
    setIsExecuting(true);
    setErrorMessage("");
    setExecutionTime(null);

    try {
      const startTime = Date.now();

      // 模拟API调用延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 模拟查询结果 - 扩展更多测试数据
      const allMockResults = [
        {
          id: 2,
          name: "测试账号",
          username: "test_user",
          password:
            "$2a$10$ELI1HaYCoHpxZz8SqvZBuOqwucHO5kMOdWBRwRJ8jywmwpY2z30S",
          status: -1,
          otp: "",
        },
        {
          id: 3,
          name: "testddd",
          username: "fsfdf",
          password:
            "$2a$10$ITmXNlNDlobxZoYqEF1xu0yey2LwrYJksiqdrxyMXZp70VLqmuOy",
          status: 1,
          otp: "",
        },
        {
          id: 4,
          name: "testccc",
          username: "sfdsfdsfd5",
          password:
            "$2a$10$O77Dqfc4DvC41EZ5SMZJ.hRgEk5wvh6AaVDL06VBoBbTEgYwxmj",
          status: 1,
          otp: "",
        },
        {
          id: 5,
          name: "testtest",
          username: "testtest",
          password:
            "$2a$10$GZgqTqpdRPoBUEeRxE65uxaLuv6hZHouJEFRZQ0oqJQSvcllL1Gm",
          status: 1,
          otp: "",
        },
        {
          id: 6,
          name: "test123",
          username: "test123",
          password:
            "$2a$10$fYyDjCiwzyjPUJeleNwjPZovJcNW0tWf154EOgw/f89pEcfVoSZuPi",
          status: 1,
          otp: "SQqtpDcUKGgh025qCBjxkmlyO67DVzxC",
        },
        {
          id: 7,
          name: "test333",
          username: "sfdsf",
          password:
            "$2a$10$qxJh.MUBHm7DRl4CZz/dvaAJLGbMsGZFyE8GwDr4XjBaybitVptm",
          status: 1,
          otp: "",
        },
        {
          id: 8,
          name: "test444",
          username: "dsfdsfsd",
          password:
            "$2a$10$THl9KHLYu4qkxktz//w4uNhMmywRKlmv6BEQ3Vzp3TxyX.mbFMlK",
          status: 1,
          otp: "",
        },
        {
          id: 9,
          name: "2222",
          username: "test333",
          password:
            "$2a$10$Nqqgr29AJpdtlIhwkwrxLmNjNCAONjctbyBxluG8ouJL3cu7yGm",
          status: 1,
          otp: "",
        },
        // 添加更多测试数据用于分页测试
        {
          id: 10,
          name: "admin",
          username: "admin",
          password: "$2a$10$AdminHashedPassword123456789",
          status: 1,
          otp: "ADMIN123456789",
        },
        {
          id: 11,
          name: "用户001",
          username: "user001",
          password: "$2a$10$User001HashedPassword123456",
          status: 1,
          otp: "",
        },
        {
          id: 12,
          name: "用户002",
          username: "user002",
          password: "$2a$10$User002HashedPassword123456",
          status: 0,
          otp: "USER002OTP123",
        },
        {
          id: 13,
          name: "测试用户A",
          username: "testA",
          password: "$2a$10$TestAHashedPassword123456789",
          status: 1,
          otp: "",
        },
        {
          id: 14,
          name: "测试用户B",
          username: "testB",
          password: "$2a$10$TestBHashedPassword123456789",
          status: -1,
          otp: "",
        },
        {
          id: 15,
          name: "开发者",
          username: "developer",
          password: "$2a$10$DeveloperHashedPassword123456",
          status: 1,
          otp: "DEV123456789",
        },
        {
          id: 16,
          name: "访客用户",
          username: "guest",
          password: "$2a$10$GuestHashedPassword123456789",
          status: 0,
          otp: "",
        },
        {
          id: 17,
          name: "系统管理员",
          username: "sysadmin",
          password: "$2a$10$SysAdminHashedPassword123456",
          status: 1,
          otp: "SYSADMIN123456",
        },
        {
          id: 18,
          name: "临时用户",
          username: "temp_user",
          password: "$2a$10$TempUserHashedPassword123456",
          status: 0,
          otp: "",
        },
        {
          id: 19,
          name: "演示账号",
          username: "demo",
          password: "$2a$10$DemoHashedPassword123456789",
          status: 1,
          otp: "",
        },
        {
          id: 20,
          name: "测试账号X",
          username: "testX",
          password: "$2a$10$TestXHashedPassword123456789",
          status: 1,
          otp: "TESTX123456789",
        },
        {
          id: 21,
          name: "客服001",
          username: "service001",
          password: "$2a$10$Service001HashedPassword1234",
          status: 1,
          otp: "",
        },
        {
          id: 22,
          name: "客服002",
          username: "service002",
          password: "$2a$10$Service002HashedPassword1234",
          status: 0,
          otp: "SERVICE002OTP",
        },
        {
          id: 23,
          name: "运营专员",
          username: "operator",
          password: "$2a$10$OperatorHashedPassword123456",
          status: 1,
          otp: "",
        },
        {
          id: 24,
          name: "数据分析师",
          username: "analyst",
          password: "$2a$10$AnalystHashedPassword123456",
          status: 1,
          otp: "ANALYST123456",
        },
        {
          id: 25,
          name: "产品经理",
          username: "pm",
          password: "$2a$10$PMHashedPassword123456789012",
          status: 1,
          otp: "",
        },
      ];

      // 设置总记录数
      setTotalRecords(allMockResults.length);

      // 根据分页参数切片数据
      const startIndex = (currentPage - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedResults = allMockResults.slice(startIndex, endIndex);

      const endTime = Date.now();
      setExecutionTime(endTime - startTime);
      setQueryResults(paginatedResults);
    } catch (error) {
      setErrorMessage(error.message || "SQL执行失败");
    } finally {
      setIsExecuting(false);
    }
  };

  // 格式化SQL
  const formatSQL = () => {
    try {
      // 使用sql-formatter库进行专业的SQL格式化
      const formatted = format(sqlCode, {
        language: "mysql",
        tabWidth: 2,
        keywordCase: "upper",
        functionCase: "upper",
        dataTypeCase: "upper",
        linesBetweenQueries: 2,
      });

      // 更新状态
      setSqlCode(formatted);

      // 如果编辑器已挂载，同步更新编辑器内容
      if (editorRef.current) {
        editorRef.current.setValue(formatted);
      }

      // 同步到外部状态
      if (setExternalSqlCode) {
        setExternalSqlCode(formatted);
      }
    } catch (error) {
      console.error("SQL格式化失败:", error);
      // 如果格式化失败，可以显示错误提示
      setErrorMessage("SQL格式化失败: " + error.message);
    }
  };

  // 基本SQL语法校验
  const validateSQL = () => {
    const errors = [];
    const sql = sqlCode.trim().toLowerCase();

    if (!sql) {
      errors.push("SQL语句不能为空");
      setValidationErrors(errors);
      return;
    }

    // 基本语法检查
    if (
      !sql.match(
        /^(select|insert|update|delete|create|drop|alter|show|describe|explain)/
      )
    ) {
      errors.push("SQL语句必须以有效的关键字开头");
    }

    if (
      sql.includes("select") &&
      !sql.includes("from") &&
      !sql.includes("dual")
    ) {
      errors.push("SELECT语句通常需要FROM子句");
    }

    // 检查括号匹配
    const openParens = (sql.match(/\(/g) || []).length;
    const closeParens = (sql.match(/\)/g) || []).length;
    if (openParens !== closeParens) {
      errors.push("括号不匹配");
    }

    // 检查引号匹配
    const singleQuotes = (sql.match(/'/g) || []).length;
    if (singleQuotes % 2 !== 0) {
      errors.push("单引号不匹配");
    }

    setValidationErrors(errors);
  };

  // 实时校验
  useEffect(() => {
    if (sqlCode.trim()) {
      validateSQL();
    } else {
      setValidationErrors([]);
    }
  }, [sqlCode]);

  // 复制到剪贴板
  const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(String(text));
      // 可以添加一个简单的提示
      const originalTitle = document.title;
      document.title = "已复制到剪贴板!";
      setTimeout(() => {
        document.title = originalTitle;
      }, 1000);
    } catch (err) {
      console.error("复制失败:", err);
      // 降级方案
      const textArea = document.createElement("textarea");
      textArea.value = String(text);
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
    }
  };

  // 截断文本并添加tooltip
  const truncateText = (text, maxLength = 30) => {
    if (!text) return "";
    const str = String(text);
    if (str.length <= maxLength) return str;
    return str.substring(0, maxLength) + "...";
  };

  return (
    <div className={`sql-content ${isDarkMode ? "dark" : "light"}`}>
      {/* SQL编辑器区域 */}
      <div className="editor-section">
        <div className="editor-header">
          <div className="editor-title">
            <span className="title-icon">📝</span>
            SQL编辑器
          </div>
          <div className="editor-actions">
            <button
              className="btn btn-outline-primary btn-sm"
              onClick={formatSQL}
              disabled={isExecuting}
            >
              <span className="btn-icon">🎨</span>
              格式化
            </button>
            <button
              className="btn btn-primary btn-sm"
              onClick={executeSQL}
              disabled={isExecuting || validationErrors.length > 0}
            >
              <span className="btn-icon">▶️</span>
              {isExecuting ? "执行中..." : "执行"}
            </button>
          </div>
        </div>

        {/* 简单的文本编辑器 - 后续会替换为Monaco */}
        <div className="editor-container">
          <MonacoEditor
            height="200px"
            language="mysql"
            theme={isDarkMode ? "vs-dark" : "vs"}
            value={sqlCode}
            onChange={(value) => handleSqlCodeChange(value || "")}
            onMount={handleEditorDidMount}
            options={editorOptions}
          />
        </div>

        {/* 校验错误提示 */}
        {validationErrors.length > 0 && (
          <div className="validation-errors">
            {validationErrors.map((error, index) => (
              <div key={index} className="error-item">
                <span className="error-icon">⚠️</span>
                {error}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 结果展示区域 */}
      <div className="results-section">
        <div className="results-header">
          <div className="results-title">
            <span className="title-icon">📊</span>
            查询结果
            {executionTime && (
              <span className="execution-time">
                (执行时间: {executionTime}ms)
              </span>
            )}
          </div>
          {queryResults.length > 0 && (
            <div className="results-count">共 {queryResults.length} 条记录</div>
          )}
        </div>

        {/* 错误信息 */}
        {errorMessage && (
          <div className="error-message">
            <span className="error-icon">❌</span>
            {errorMessage}
          </div>
        )}

        {/* 结果表格 */}
        {queryResults.length > 0 && (
          <div className="table-container">
            <table className="table table-striped table-hover">
              <thead>
                <tr>
                  <th>No.</th>
                  {Object.keys(queryResults[0]).map((key) => (
                    <th key={key}>{key}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {queryResults.map((row, index) => (
                  <tr key={index}>
                    <td>{(currentPage - 1) * pageSize + index + 1}</td>
                    {Object.entries(row).map(([key, value]) => (
                      <td
                        key={key}
                        title={`点击复制: ${String(value)}`}
                        onClick={() => copyToClipboard(value)}
                        className="copyable-cell"
                      >
                        {truncateText(value)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* 分页组件 */}
        {queryResults.length > 0 && (
          <div className="pagination-container">
            <div className="pagination-info">
              <span className="records-info">
                显示第 {(currentPage - 1) * pageSize + 1} -{" "}
                {Math.min(currentPage * pageSize, totalRecords)} 条， 共{" "}
                {totalRecords} 条记录
              </span>
            </div>
            <div className="pagination-controls">
              <div className="page-size-selector">
                <span>每页显示：</span>
                <select
                  value={pageSize}
                  onChange={(e) => {
                    setPageSize(Number(e.target.value));
                    setCurrentPage(1);
                  }}
                  className="page-size-select"
                >
                  <option value={5}>5 条</option>
                  <option value={10}>10 条</option>
                  <option value={20}>20 条</option>
                  <option value={50}>50 条</option>
                  <option value={100}>100 条</option>
                </select>
              </div>
              <div className="page-navigation">
                <button
                  className="page-btn"
                  onClick={() => setCurrentPage(1)}
                  disabled={currentPage === 1}
                >
                  首页
                </button>
                <button
                  className="page-btn"
                  onClick={() =>
                    setCurrentPage((prev) => Math.max(1, prev - 1))
                  }
                  disabled={currentPage === 1}
                >
                  上一页
                </button>
                <div className="page-input-group">
                  <span>第</span>
                  <input
                    type="number"
                    min="1"
                    max={Math.ceil(totalRecords / pageSize)}
                    value={currentPage}
                    onChange={(e) => {
                      const page = Number(e.target.value);
                      if (
                        page >= 1 &&
                        page <= Math.ceil(totalRecords / pageSize)
                      ) {
                        setCurrentPage(page);
                      }
                    }}
                    className="page-input"
                  />
                  <span>页 / 共 {Math.ceil(totalRecords / pageSize)} 页</span>
                </div>
                <button
                  className="page-btn"
                  onClick={() =>
                    setCurrentPage((prev) =>
                      Math.min(Math.ceil(totalRecords / pageSize), prev + 1)
                    )
                  }
                  disabled={currentPage >= Math.ceil(totalRecords / pageSize)}
                >
                  下一页
                </button>
                <button
                  className="page-btn"
                  onClick={() =>
                    setCurrentPage(Math.ceil(totalRecords / pageSize))
                  }
                  disabled={currentPage >= Math.ceil(totalRecords / pageSize)}
                >
                  末页
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 空状态 */}
        {queryResults.length === 0 && !errorMessage && !isExecuting && (
          <div className="empty-state">
            <div className="empty-icon">📋</div>
            <div className="empty-text">暂无查询结果</div>
            <div className="empty-subtext">请编写SQL语句并点击执行按钮</div>
          </div>
        )}

        {/* 加载状态 */}
        {isExecuting && (
          <div className="loading-state">
            <div className="loading-spinner"></div>
            <div className="loading-text">正在执行SQL查询...</div>
          </div>
        )}
      </div>

      <style jsx>{`
        .sql-content {
          height: 100%;
          display: flex;
          flex-direction: column;
          gap: 20px;
          padding: 20px;
          background: var(--bg-primary);
          color: var(--text-primary);
        }

        .editor-section {
          flex: 0 0 auto;
          border: 1px solid var(--border-color);
          border-radius: 8px;
          overflow: hidden;
        }

        .editor-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          background: var(--bg-secondary);
          border-bottom: 1px solid var(--border-color);
        }

        .editor-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 500;
        }

        .title-icon {
          font-size: 16px;
        }

        .editor-actions {
          display: flex;
          gap: 8px;
        }

        .btn-icon {
          margin-right: 4px;
        }

        .editor-container {
          position: relative;
          border: 1px solid var(--border-color);
          border-radius: 4px;
          overflow: hidden;
        }

        .editor-loading {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 200px;
          background: var(--bg-primary);
          color: var(--text-secondary);
          gap: 12px;
        }

        .editor-loading .loading-spinner {
          width: 24px;
          height: 24px;
          border: 2px solid var(--border-color);
          border-top: 2px solid var(--primary-color);
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }

        .validation-errors {
          padding: 12px 16px;
          background: rgba(220, 53, 69, 0.1);
          border-top: 1px solid var(--border-color);
        }

        .error-item {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #dc3545;
          font-size: 14px;
          margin-bottom: 4px;
        }

        .error-item:last-child {
          margin-bottom: 0;
        }

        .error-icon {
          font-size: 14px;
        }

        .results-section {
          flex: 1;
          display: flex;
          flex-direction: column;
          border: 1px solid var(--border-color);
          border-radius: 8px;
          overflow: hidden;
        }

        .results-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          background: var(--bg-secondary);
          border-bottom: 1px solid var(--border-color);
        }

        .results-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 500;
        }

        .execution-time {
          color: var(--text-secondary);
          font-size: 12px;
          margin-left: 8px;
        }

        .results-count {
          color: var(--text-secondary);
          font-size: 14px;
        }

        .error-message {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 16px;
          background: rgba(220, 53, 69, 0.1);
          color: #dc3545;
          border-bottom: 1px solid var(--border-color);
        }

        .table-container {
          flex: 1;
          overflow: auto;
        }

        .table {
          margin: 0;
          background: var(--bg-primary);
          color: var(--text-primary);
        }

        .table th {
          background: var(--bg-secondary);
          border-color: var(--border-color);
          font-weight: 500;
          position: sticky;
          top: 0;
          z-index: 10;
        }

        .table td {
          border-color: var(--border-color);
          max-width: 200px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .copyable-cell {
          cursor: pointer;
          position: relative;
          transition: background-color 0.2s ease;
        }

        .copyable-cell:hover {
          background-color: var(--bg-hover) !important;
        }

        .copyable-cell:active {
          background-color: var(--primary-color);
          color: white;
          transform: scale(0.98);
        }

        .table-striped tbody tr:nth-of-type(odd) {
          background: var(--bg-secondary);
        }

        .table-hover tbody tr:hover {
          background: var(--bg-hover);
        }

        .empty-state {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 60px 20px;
          color: var(--text-secondary);
        }

        .empty-icon {
          font-size: 48px;
          margin-bottom: 16px;
          opacity: 0.5;
        }

        .empty-text {
          font-size: 18px;
          font-weight: 500;
          margin-bottom: 8px;
        }

        .empty-subtext {
          font-size: 14px;
          opacity: 0.7;
        }

        .loading-state {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 60px 20px;
        }

        .loading-spinner {
          width: 32px;
          height: 32px;
          border: 3px solid var(--border-color);
          border-top: 3px solid var(--primary-color);
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-bottom: 16px;
        }

        @keyframes spin {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(360deg);
          }
        }

        .loading-text {
          color: var(--text-secondary);
          font-size: 14px;
        }

        /* 主题变量 */
        .light {
          --bg-primary: #ffffff;
          --bg-secondary: #f8f9fa;
          --bg-hover: rgba(0, 0, 0, 0.05);
          --text-primary: #212529;
          --text-secondary: #6c757d;
          --border-color: #dee2e6;
          --primary-color: #0d6efd;
        }

        .dark {
          --bg-primary: #1a1a1a;
          --bg-secondary: #2d2d2d;
          --bg-hover: rgba(255, 255, 255, 0.1);
          --text-primary: #ffffff;
          --text-secondary: #adb5bd;
          --border-color: #404040;
          --primary-color: #0d6efd;
        }

        /* 分页组件样式 */
        .pagination-container {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          background: var(--bg-secondary);
          border-top: 1px solid var(--border-color);
          flex-wrap: wrap;
          gap: 12px;
        }

        .pagination-info {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .records-info {
          font-size: 14px;
          color: var(--text-secondary);
        }

        .pagination-controls {
          display: flex;
          align-items: center;
          gap: 16px;
          flex-wrap: wrap;
        }

        .page-size-selector {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          color: var(--text-secondary);
        }

        .page-size-select {
          padding: 4px 8px;
          border: 1px solid var(--border-color);
          border-radius: 4px;
          background: var(--bg-primary);
          color: var(--text-primary);
          font-size: 14px;
          cursor: pointer;
        }

        .page-size-select:focus {
          outline: none;
          border-color: var(--primary-color);
        }

        .page-navigation {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .page-btn {
          padding: 6px 12px;
          border: 1px solid var(--border-color);
          border-radius: 4px;
          background: var(--bg-primary);
          color: var(--text-primary);
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .page-btn:hover:not(:disabled) {
          background: var(--bg-hover);
          border-color: var(--primary-color);
        }

        .page-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .page-input-group {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 14px;
          color: var(--text-secondary);
        }

        .page-input {
          width: 60px;
          padding: 4px 8px;
          border: 1px solid var(--border-color);
          border-radius: 4px;
          background: var(--bg-primary);
          color: var(--text-primary);
          font-size: 14px;
          text-align: center;
        }

        .page-input:focus {
          outline: none;
          border-color: var(--primary-color);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
          .sql-content {
            padding: 12px;
            gap: 12px;
          }

          .editor-header,
          .results-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
          }

          .editor-actions {
            width: 100%;
            justify-content: flex-end;
          }

          .table-container {
            font-size: 12px;
          }

          .table td {
            max-width: 120px;
          }

          .pagination-container {
            flex-direction: column;
            align-items: stretch;
            gap: 12px;
          }

          .pagination-controls {
            justify-content: center;
            flex-wrap: wrap;
          }

          .page-navigation {
            flex-wrap: wrap;
            justify-content: center;
          }
        }
      `}</style>
    </div>
  );
}
